<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <img src="/favicon.ico" alt="Logo" class="logo" />
        <h1 class="title">学生管理系统</h1>
        <p class="subtitle">Student Management System</p>
      </div>
      
      <a-form
        ref="formRef"
        :model="loginForm"
        :rules="rules"
        @finish="handleLogin"
        class="login-form"
      >
        <a-form-item name="username">
          <a-input
            v-model:value="loginForm.username"
            size="large"
            placeholder="请输入用户名"
          >
            <template #prefix>
              <UserOutlined class="input-icon" />
            </template>
          </a-input>
        </a-form-item>
        
        <a-form-item name="password">
          <a-input-password
            v-model:value="loginForm.password"
            size="large"
            placeholder="请输入密码"
          >
            <template #prefix>
              <LockOutlined class="input-icon" />
            </template>
          </a-input-password>
        </a-form-item>
        
        <a-form-item name="captcha" v-if="showCaptcha">
          <a-row :gutter="8">
            <a-col :span="14">
              <a-input
                v-model:value="loginForm.captcha"
                size="large"
                placeholder="请输入验证码"
              >
                <template #prefix>
                  <SafetyOutlined class="input-icon" />
                </template>
              </a-input>
            </a-col>
            <a-col :span="10">
              <div class="captcha-image" @click="refreshCaptcha">
                <img :src="captchaUrl" alt="验证码" />
              </div>
            </a-col>
          </a-row>
        </a-form-item>
        
        <a-form-item>
          <a-checkbox v-model:checked="loginForm.remember">
            记住密码
          </a-checkbox>
          <a class="forgot-password" @click="handleForgotPassword">
            忘记密码？
          </a>
        </a-form-item>
        
        <a-form-item>
          <a-button
            type="primary"
            html-type="submit"
            size="large"
            :loading="loading"
            class="login-button"
          >
            登录
          </a-button>
        </a-form-item>
      </a-form>
      
      <div class="login-footer">
        <p>&copy; 2024 学生管理系统. All rights reserved.</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { UserOutlined, LockOutlined, SafetyOutlined } from '@ant-design/icons-vue'
import { useUserStore } from '@/store'
import { authApi } from '@/api'

const router = useRouter()
const userStore = useUserStore()

// 表单引用
const formRef = ref()

// 加载状态
const loading = ref(false)

// 是否显示验证码
const showCaptcha = ref(false)

// 验证码URL
const captchaUrl = ref('')

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: '',
  captcha: '',
  remember: false
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
}

// 处理登录
const handleLogin = async (values) => {
  try {
    loading.value = true
    
    // 构建登录请求数据
    const loginData = {
      username: values.username,
      password: values.password,
      rememberMe: values.remember
    }
    
    // 如果显示验证码，则添加验证码信息
    if (showCaptcha.value && values.captcha) {
      loginData.captcha = values.captcha
      loginData.captchaKey = 'captcha_key_' + Date.now() // 实际项目中应该从后端获取
    }
    
    // 调用登录API
    const response = await authApi.login(loginData)
    
    // 保存登录信息到store
    userStore.setLoginInfo(response)
    
    message.success('登录成功')
    
    // 跳转到dashboard页面
    router.push('/dashboard')
    
  } catch (error) {
    console.error('登录失败:', error)
    
    // 根据错误码显示不同的错误信息
    let errorMessage = '登录失败'
    if (error.response && error.response.data) {
      const { code, message: msg } = error.response.data
      switch (code) {
        case 2004:
          errorMessage = '用户名或密码错误'
          break
        case 2006:
          errorMessage = '账户已锁定，请联系管理员'
          break
        case 2007:
          errorMessage = '账户已禁用，请联系管理员'
          break
        case 2008:
          errorMessage = '密码错误'
          break
        default:
          errorMessage = msg || '登录失败，请稍后重试'
      }
    }
    
    message.error(errorMessage)
    
    // 登录失败后显示验证码
    showCaptcha.value = true
    refreshCaptcha()
  } finally {
    loading.value = false
  }
}

// 刷新验证码
const refreshCaptcha = () => {
  // 模拟验证码URL
  captchaUrl.value = `data:image/svg+xml;base64,${btoa(`
    <svg width="120" height="40" xmlns="http://www.w3.org/2000/svg">
      <rect width="120" height="40" fill="#f0f0f0"/>
      <text x="60" y="25" text-anchor="middle" font-size="16" fill="#666">
        ${Math.random().toString(36).substr(2, 4).toUpperCase()}
      </text>
    </svg>
  `)}`
}

// 忘记密码
const handleForgotPassword = () => {
  message.info('请联系管理员重置密码')
}

// 组件挂载时的操作
onMounted(() => {
  // 如果已经登录，直接跳转到首页
  if (userStore.isLoggedIn) {
    router.push('/')
  }
})
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.login-box {
  width: 100%;
  max-width: 400px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  padding: 40px;
}

.login-header {
  text-align: center;
  margin-bottom: 32px;
}

.logo {
  width: 64px;
  height: 64px;
  margin-bottom: 16px;
}

.title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0 0 8px 0;
}

.subtitle {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.login-form {
  margin-bottom: 24px;
}

.input-icon {
  color: #999;
}

.captcha-image {
  height: 40px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fafafa;
}

.captcha-image img {
  max-width: 100%;
  max-height: 100%;
}

.forgot-password {
  float: right;
  color: #1890ff;
  text-decoration: none;
}

.forgot-password:hover {
  text-decoration: underline;
}

.login-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
  font-weight: 500;
}

.login-footer {
  text-align: center;
  color: #999;
  font-size: 12px;
}

.login-footer p {
  margin: 0;
}

@media (max-width: 480px) {
  .login-box {
    padding: 24px;
  }
  
  .title {
    font-size: 20px;
  }
}
</style>